//
//  ZJKComposeToolBar.swift
//  MicroBlog
//
//  Created by VAD on 16/4/25.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

// 使用枚举去区分不同的按钮点击

/// <#Description#>
///
/// - Picture:  图片
/// - Mention:  @
/// - Trend:    话题
/// - Emoticon: 表情
/// - Add:      加号
enum ZJKComposeToolBarButtonType: Int {
    case Picture = 0, Mention, Trend, Emoticon, Add
}

class ZJKComposeToolBar: UIStackView {

    
    var isSystemKeyboard: Bool = true {
        didSet{
            let button = self.viewWithTag((ZJKComposeToolBarButtonType.Emoticon).rawValue) as? UIButton
            
            var name = "compose_keyboardbutton_background"
            // 调整表情按钮的图标
            if isSystemKeyboard {
                // 显示笑脸图标
                name = "compose_emoticonbutton_background"
            }
            button?.setImage(UIImage(named: "\(name)_highlighted"), forState: UIControlState.Highlighted)
            button?.setImage(UIImage(named: name), forState: UIControlState.Normal)

        }
        
        }
    
    // 按钮点击要执行的闭包
    var buttonClickClosure: ((type: ZJKComposeToolBarButtonType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        // 设置子控件相等并且填充父控件
        distribution = .FillEqually
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置视图
    private func setupUI(){
        backgroundColor = UIColor.redColor()
        
        addChildButton("compose_toolbar_picture", type: .Picture)
        addChildButton("compose_mentionbutton_background", type: .Mention)
        addChildButton("compose_trendbutton_background", type: .Trend)
        addChildButton("compose_emoticonbutton_background", type: .Emoticon)
        addChildButton("compose_add_background", type: .Add)
    }
    
    /// 通过图片名字添加子控件
    ///
    /// - parameter imgNamed: <#imgNamed description#>
    private func addChildButton(imgNamed: String,type: ZJKComposeToolBarButtonType) {
        let button = UIButton()
        
        button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        // 取到枚举的原始值
        button.tag = type.rawValue
        // 设置不同状态的图片
        button.setImage(UIImage(named: imgNamed), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "\(imgNamed)_highlighted"), forState: UIControlState.Highlighted)
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Highlighted)
        
        addArrangedSubview(button)
    }
    
    
    @objc private func childButtonClick(button: UIButton) {
        // 要在此回调，就需要在此执行闭包
        buttonClickClosure?(type: ZJKComposeToolBarButtonType(rawValue: button.tag)!)
    }

}
